package com.demo.service;

import com.demo.annotation.DataSourceRouter;
import com.demo.entity.User;
import com.demo.exception.SrvErrCode;
import com.demo.exception.SrvException;
import com.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by hardy
 * 2018/6/8 下午4:14
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    // 主库测试
    @Override
    public User getUserM(long id) {
        return userMapper.findOne(id);
    }

    // 从库测试 增加注解 默认 type=DataSourceType.SLAVE
    @Override
    @DataSourceRouter
    public User getUserS(long id) {
        return userMapper.findOne(id);
    }

    // 1.测试事务 2.测试mapper provider
    @Override
    @Transactional
    public long saveUser(String name, int age) {
        User user = new User();
        user.setName(name);
        user.setAge(age);
        userMapper.insert(user);

        if (age > 100)
            throw new SrvException(SrvErrCode.PARAM_ERR);
        return user.getId();
    }

    // 事务测试
    @Override
    @Transactional
    public void updateUser(long id, String name, int age) {
        User user = userMapper.findOne(id);
        user.setName(name);
        user.setAge(age);
        userMapper.update(user);
    }
}
